/**
  HomeMade by shoe[box]
 
  Redistribution and use in source and binary forms, with or without 
  modification, are permitted provided that the following conditions are
  met:

  * Redistributions of source code must retain the above copyright notice, 
    this list of conditions and the following disclaimer.
  
  * Redistributions in binary form must reproduce the above copyright
    notice, this list of conditions and the following disclaimer in the 
    documentation and/or other materials provided with the distribution.
  
  * Neither the name of shoe[box] nor the names of its 
    contributors may be used to endorse or promote products derived from 
    this software without specific prior written permission.

  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
  IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
  THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR 
  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

package org.shoebox.guacamole.view.abstracts {

	import com.adobe.utils.AGALMiniAssembler;
	import org.shoebox.guacamole.core.RenderTask;
	import org.shoebox.guacamole.interfaces.IRenderable;
	import org.shoebox.utils.logger.Logger;
	import flash.display3D.Context3DProgramType;
	import flash.display3D.Context3DVertexBufferFormat;
	import flash.display3D.IndexBuffer3D;
	import flash.display3D.Program3D;
	import flash.display3D.VertexBuffer3D;
	import flash.geom.Matrix3D;

	/**
	* org.shoebox.guacamole.view.abstracts.AMesh
	* @author shoebox
	*/
	public class GuaMesh extends GuaProjectable implements IRenderable{
		
		public var castShadow					: Boolean = false;
		public var tilePosY : int , tilePosX : int;
		public var iBufferNormalsSize			: int;
		public var iBufferUVsSize				: int;
		public var iBufferVerticesSize			: int;
		public var bufferFormatNormals			: String;
		public var bufferFormatUV				: String;
		public var bufferFormatVertices			: String;
		public var vIndexs					: Vector.<uint> = new Vector.<uint>( );
		public var vUVCoords					: Vector.<Number>;
		public var vVerticesCoords				: Vector.<Number>;
		
		protected var _bInvalidateKernel			: Boolean;
		protected var _bInvalidateNormals			: Boolean;
		protected var _bInvalidateUVs				: Boolean;
		protected var _bInvalidateVertices			: Boolean;
		protected var _bInvalidateIndexs			: Boolean;
		
		protected var _vNormalsCoords				: Vector.<Number>;
		protected var _bufferNormals				: VertexBuffer3D;
		protected var _bufferUVs					: VertexBuffer3D;
		protected var _bufferVertices				: VertexBuffer3D;
		protected var _bufferIndexs				: IndexBuffer3D;
		protected var _pProgram					: Program3D;
		protected var _sName						: String;
		
		// -------o constructor
		
			/**
			* Constructor of the AMesh class
			*
			* @public
			* @return	void
			*/
			public function GuaMesh( ) : void {
				super( );
			}

		// -------o public
			
			/**
			* onPreRender function
			* @public
			* @param 
			* @return
			*/
			public function onPreRender() : Boolean {
				return true;
			}
			
			/**
			* setIndexs function
			* @public
			* @param 
			* @return
			*/
			final public function setIndexs( v : Vector.<uint> ) : void {
				
				vIndexs = v;
				_bInvalidateIndexs = true;
			}
			
			/**
			* getIndexs function
			* @public
			* @param 
			* @return
			*/
			final public function getIndexs( b : Boolean = true ) :  Vector.<uint> {
				return b ? vIndexs.slice( ) : vIndexs;
			}
			
			
			/**
			* getIndexBuffer function
			* @public
			* @param 
			* @return
			*/
			final public function getIndexBuffer() : IndexBuffer3D {
				
				if( !_bInvalidateIndexs )
					return _bufferIndexs;
					
				var l : int = vIndexs.length;
				_bInvalidateIndexs = false;
				
				_bufferIndexs = scene.refContext3D.createIndexBuffer( l );
				_bufferIndexs.uploadFromVector( vIndexs , 0 , l );
				return _bufferIndexs;
			}
			
			
			/**
			* setVertex function
			* @public
			* @param 
			* @return
			*/
			final public function setVertices( v : Vector.<Number> , bufferFormatVertices : String = Context3DVertexBufferFormat.FLOAT_3 ) : void {
				
				vVerticesCoords = v;	
				this.bufferFormatVertices = bufferFormatVertices;
				iBufferVerticesSize = _convert( bufferFormatVertices );
				_bInvalidateProjVertices = true;
				_bInvalidateVertices = true;
			}
			
			/**
			* getVerticesBuffer function
			* @public
			* @param 
			* @return
			*/
			final public function getVerticesBuffer() : VertexBuffer3D {
				
				if( _bInvalidateVertices ){
					
					if( _bufferVertices )
						_bufferVertices.dispose( );
						_bufferVertices = _generateBuffer( vVerticesCoords , iBufferVerticesSize );
						//_bufferVertices = BufferCacher.getVertexBuffer( this, scene );
						
					_bInvalidateVertices = false;
				}
				
				return _bufferVertices;
				
			}
			
			
			/**
			* setUvs function
			* @public
			* @param 
			* @return
			*/
			final public function setUvs( v : Vector.<Number> , bufferFormatUV : String = Context3DVertexBufferFormat.FLOAT_3 ) : void {
				vUVCoords = v;
				this.bufferFormatUV = bufferFormatUV;
				iBufferUVsSize = _convert( bufferFormatUV );
				_bInvalidateUVs = true;
			}
			
			/**
			* getUVs function
			* @public
			* @param 
			* @return
			*/
			final public function getUVs() : Vector.<Number> {
				return vUVCoords;
			}
			
			/**
			* getVerticesBuffer function
			* @public
			* @param 
			* @return
			*/
			final public function getUVsBuffer() : VertexBuffer3D {
				
				if( _bInvalidateUVs ){
					
					if( _bufferUVs )
						_bufferUVs.dispose( );
						_bufferUVs = _generateBuffer( vUVCoords , iBufferUVsSize );
						//_bufferUVs = BufferCacher.getUVBuffer( this, scene );
						
					_bInvalidateUVs = false;
				}
				
				return _bufferUVs;
			}
			
			/**
			* setNormals function
			* @public
			* @param 
			* @return
			*/
			final public function setNormals( v : Vector.<Number> , bufferFormatNormals : String ) : void {
				_vNormalsCoords = v;
				this.bufferFormatNormals = bufferFormatNormals;
				iBufferNormalsSize = _convert( bufferFormatNormals );
				_bInvalidateNormals = true;
			}
			
			/**
			* getNormalsBuffer function
			* @public
			* @param 
			* @return
			*/
			final public function getNormalsBuffer() : VertexBuffer3D {
				
				if( _bInvalidateNormals ){
					
					if( _bufferNormals )
						_bufferNormals.dispose( );
						_bufferNormals = _generateBuffer( _vNormalsCoords , iBufferNormalsSize );
					
					_bInvalidateNormals = false;
				}
				return _bufferNormals;
			}
			
			/**
			* render function
			* @public
			* @param 
			* @return
			*/
			override public function render( oTask : RenderTask ) : void {
				
				//
					if( vIndexs.length == 0 )
						return;
				
				//
					if( !onPreRender( ) )	
						return;
					
				// Preprod
					oTask.addMaterial( material );
					material.preprod( this );
					
				//	
					scene.refContext3D.setProgram( getProgram( oTask.agalVertices ) );
					scene.refContext3D.setProgramConstantsFromMatrix ( Context3DProgramType.VERTEX , 0 , getProjectedMatrix ( oTask.oCam ) , true );
					scene.refContext3D.drawTriangles( getIndexBuffer( ) );
					
				//
					material.postprod( this );
				
			}
			
			/**
			* getProgram function
			* @public
			* @param 
			* @return
			*/
			final public function getProgram( vertAgal : AGALMiniAssembler ) : Program3D {
				
				if( _bInvalidateKernel || material.invalidateProgram )
					_pProgram = material.getProgram( vertAgal );
				
				_bInvalidateKernel = false;
				return _pProgram;
				
			}
			
			/**
			* getProjectVertices function
			* @public
			* @param 
			* @return
			*/
			internal var vRes : Vector.<Number>;
			final public function getProjectVertices( ) : Vector.<Number> {
				
				var mat : Matrix3D = getProjection( );
				var i : int = 0 , l : int = vVerticesCoords.length / iBufferVerticesSize;
				
				if( !vRes )
					vRes = new Vector.<Number>( l * iBufferVerticesSize , true );
					
				var inc : int;
				for( i ; i < l ; i++ ){
					
					inc = i * iBufferVerticesSize;
						
					vRes[ inc ] 		= vVerticesCoords[ inc ];
					vRes[ inc + 1 ] 	= vVerticesCoords[ inc + 1 ];
					vRes[ inc + 2 ] 	= 0;
					
				}
				
				mat.transformVectors( vRes , vRes );
				
				return vRes;
			}	
			
			/**
			* Setter of the mesh name
			* @public
			* @param	s : Mesh name			( String ) 
			* @return	void
			*/
			final public function set name( s : String ) : void {
				_sName = s;
			}
			
			/**
			* Getter of the mesh name
			*  
			* @public
			* @return mesh name		( String )
			*/
			final public function get name() : String {
				return _sName;
			}
			
		// -------o protected
			
			/**
			* 
			*
			* @param 
			* @return
			*/
			final protected function _generateBuffer( source : Vector.<Number> , bufferSize : int ) : VertexBuffer3D {
				
				var 	iNumVertices 	: int = source.length / bufferSize;
				var 	vBuffer : VertexBuffer3D = scene.refContext3D.createVertexBuffer ( iNumVertices , bufferSize );
						vBuffer.uploadFromVector ( source , 0 , iNumVertices );
					
				return vBuffer;
			}
			
			/**
			* 
			*
			* @param 
			* @return
			*/
			final protected function _convert( s : String ) : int {
				
				switch( s ){
					case Context3DVertexBufferFormat.FLOAT_1:
						return 1;
						break;
						
					case Context3DVertexBufferFormat.FLOAT_2:
						return 2;
						break;
						
					case Context3DVertexBufferFormat.FLOAT_3:
						return 3;
						break;
						
					case Context3DVertexBufferFormat.FLOAT_4:
						return 4;
						break;
				}
				
				return -1;
			}
			
		// -------o misc

			public static function trc(...args : *) : void {
				Logger.log(GuaMesh, args);
			}
	}
}
